package com.aurora.leetcode.answer;

/**
 * @author : Aurora
 * @date : 2024/5/24 17:13
 * @description
 * <p>541. 反转字符串 II</p>
 * <p>给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。</p>
 * <p>如果剩余字符少于 k 个，则将剩余字符全部反转。</p>
 * <p>如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。</p>
 * <p>示例 1：</p>
 * <p>输入：s = "abcdefg", k = 2</p>
 * <p>输出："bacdfeg"</p>
 * <p>示例 2：</p>
 * <p>输入：s = "abcd", k = 2</p>
 * <p>输出："bacd"</p>
 */
public class ReverseStr_541 {
    public String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        int length = charArray.length;
        int start = 0, end = 0;
        int count = 0;
        while(length > 0){
            ++count;
            start = (count-1)*2*k;
            end =start +  k-1;
            reverse(charArray, start, end);
            length -= 2*k;
        }
        return new String(charArray);
    }

    public void reverse(char[] chars, int start, int end){
        if(end >= chars.length){
            end = chars.length - 1;
        }
        for(;start<end;++start,--end){
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
        }
    }

    public static void main(String[] args) {

        ReverseStr_541 obj = new ReverseStr_541();
//        String s = "abcdefg";
        String s = "abcd";
        int k = 3;
        System.out.println(obj.reverseStr(s, k));
    }
}
